package com.data.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/**
 * @author Administrator
 */
public class SendMailUtils {
    private final static String username = "safefish@forkeji.com";
    private final static String password = "Aqy1357924680";
    private final static String protocol = "smtp";
    private final static String host = "smtp.exmail.qq.com";
    private final static String port = "465";
    private static String rootUrl = getUtl();
    private final static String url = rootUrl + "android/registerAction/activeEmail?email=";
    private final static String url1 = rootUrl + "android/fillMassageAction/activeEmail?email=";
    private final static String url2 = rootUrl + "indexUserAction/user/activeEmailChange?email=";

    /**
     * 获取项目的URL，根据操作系统来判定
     *
     * @return
     */
    private static String getUtl() {
        String os = System.getProperty("os.name");

        if (os.toLowerCase().startsWith("win")) {
            return "http://localhost:8080/";
        } else {
            return "http://app.forkeji.com/";
        }

    }

    /**
     * 通过邮箱生成激活码
     *
     * @param email
     * @return
     */
    public static String getActive(String email) {
        Calendar c = Calendar.getInstance();
        long time = c.getTimeInMillis();
        StringBuilder token = new StringBuilder(Md5CodeUtils.md5(email + time));
        token.append(UUID.randomUUID().toString());
        String code = token.toString();
        //将加密后中的+号替换为s，因为+在URL中无法请求到
        code = code.replace("+", "s");
        return code;
    }


    /**
     * 发送邮件
     *
     * @param subject  邮箱主题
     * @param to       收件人
     * @param contents 发送HTML格式的内容
     * @return
     */
    private static boolean sendMails(String subject, String to, String contents) {
        try {
            Properties props = new Properties();
            props.put("username", username);
            props.put("password", password);
            props.put("mail.transport.protocol", protocol);
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.port", port);

            //开启SSL协议，如果不需要开启SSL协议，请屏蔽此行代码
            props = startSSL(props);

            Session mailSession = Session.getDefaultInstance(props);
            Transport transport = mailSession.getTransport(protocol);
            //链接到服务器
            transport.connect(host, username, password);
            Message msg = new MimeMessage(mailSession);
            msg.setFrom(new InternetAddress(username));
            msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            msg.setSubject(subject);
            msg.setContent(contents, "text/html;charset=UTF-8");
            //保存邮件信息
            msg.saveChanges();
            //发送邮件
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;


    }

    private static Properties startSSL(Properties props) {
        //开启ssl协议
        props.setProperty("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        return props;
    }


    /**
     * 注册账号fa送的邮件
     *
     * @param to 收件人邮箱地址
     */
    public static boolean sendMail(String to, String code) {
        String subject = "安全鱼开放平台账号激活链接";
        String dateString = getNowDateUtils();
        String contents = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>邮箱激活样式</title>\n" +
                "    <style>\n" +
                "        .bg{\n" +
                "            padding: 20px 30px;\n" +
                "            width: 1000px;\n" +
                "            background: -webkit-repeating-linear-gradient(#d6e4ed,white); /* Safari 5.1 - 6.0 */\n" +
                "            background: -o-repeating-linear-gradient(#d6e4ed , white); /* Opera 11.1 - 12.0 */\n" +
                "            background: -moz-repeating-linear-gradient(#d6e4ed , white); /* Firefox 3.6 - 15 */\n" +
                "            background: repeating-linear-gradient(#d6e4ed,  white); /* 标准的语法（必须放在最后） */\n" +
                "            overflow: hidden;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<div class=\"bg\">\n" +
                "    <p>尊敬的用户:</p>\n" +
                "    <p>您好！恭喜你注册成为安全鱼开放平台的开发者。</p>\n" +
                "    <p>如果您没有访问过安全鱼开放平台，或没有进行上述操作，请忽略这封邮件。您不需要退订或进行其他进一步的操作。</p>\n" +
                "    <p>这是一封注册认证邮件，请点击以下链接确认：</p>\n" +
                "<a href=" + url + to + "&code=" + code + ">" + url + to + "&code=" + code + "</a>" +
                "    <p>如果链接不能点击，请复制地址到浏览器，然后直接打开。</p>\n" +
                "    <p>上述链接48小时有效。如果激活链接失效，请登录网站 <a href='http://app.forkeji.com'>http://app.forkeji.com </a>重新申请认证。</p>\n" +
                "    <p>感谢您注册安全鱼开放平台！</p>\n" +
                "    <div style=\"text-align: right;\">\n" +
                "        <p>安全鱼开放平台项目组</p>\n" +
                "        <p>" + dateString + "</p>\n" +
                "    </div>\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>";
        boolean bool = sendMails(subject, to, contents);
        return bool;

    }

    /**
     * 注册账号申请开发者账号发送的邮箱的邮件
     *
     * @param to 收件人邮箱地址
     */
    public static boolean sendMailMassage(String id, String to, String code, int type) {
        String url = url1;
        String subject = "安全鱼开放平台绑定账号激活链接";
        String dateString = getNowDateUtils();
        String contents = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>邮箱激活样式</title>\n" +
                "    <style>\n" +
                "        .bg{\n" +
                "            padding: 20px 30px;\n" +
                "            width: 1000px;\n" +
                "            background: -webkit-repeating-linear-gradient(#d6e4ed,white); /* Safari 5.1 - 6.0 */\n" +
                "            background: -o-repeating-linear-gradient(#d6e4ed , white); /* Opera 11.1 - 12.0 */\n" +
                "            background: -moz-repeating-linear-gradient(#d6e4ed , white); /* Firefox 3.6 - 15 */\n" +
                "            background: repeating-linear-gradient(#d6e4ed,  white); /* 标准的语法（必须放在最后） */\n" +
                "            overflow: hidden;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<div class=\"bg\">\n" +
                "    <p>尊敬的用户:</p>\n" +
                "    <p>您好！恭喜你注册成为安全鱼开放平台的开发者。</p>\n" +
                "    <p>如果您没有访问过安全鱼开放平台，或没有进行上述操作，请忽略这封邮件。您不需要退订或进行其他进一步的操作。</p>\n" +
                "    <p>这是一封注册认证邮件，请点击以下链接确认：</p>\n" +
                "<a href=" + url + to + "&id=" + id + "&code=" + code + "&type=" + type + ">" + url + to + "&id=" + id + "&code=" + code + "&type=" + type + "</a>" +
                "    <p>如果链接不能点击，请复制地址到浏览器，然后直接打开。</p>\n" +
                "    <p>上述链接48小时有效。如果激活链接失效，请登录网站 <a href='http://app.forkeji.com'>http://app.forkeji.com </a>重新申请认证。</p>\n" +
                "    <p>感谢您注册安全鱼开放平台！</p>\n" +
                "    <div style=\"text-align: right;\">\n" +
                "        <p>安全鱼开放平台项目组</p>\n" +
                "        <p>" + dateString + "</p>\n" +
                "    </div>\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>";


        boolean bool = sendMails(subject, to, contents);
        return bool;

    }


    public static boolean sendChangeEmail(String to, String code) {
        String url = url2;
        String subject = "安全鱼开放平台账号激活链接";
        String dateString = getNowDateUtils();
        String contents = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>邮箱激活样式</title>\n" +
                "    <style>\n" +
                "        .bg{\n" +
                "            padding: 20px 30px;\n" +
                "            width: 1000px;\n" +
                "            background: -webkit-repeating-linear-gradient(#d6e4ed,white); /* Safari 5.1 - 6.0 */\n" +
                "            background: -o-repeating-linear-gradient(#d6e4ed , white); /* Opera 11.1 - 12.0 */\n" +
                "            background: -moz-repeating-linear-gradient(#d6e4ed , white); /* Firefox 3.6 - 15 */\n" +
                "            background: repeating-linear-gradient(#d6e4ed,  white); /* 标准的语法（必须放在最后） */\n" +
                "            overflow: hidden;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<div class=\"bg\">\n" +
                "    <p>尊敬的用户:</p>\n" +
                "    <p>您好！恭喜你注册成为安全鱼开放平台的开发者。</p>\n" +
                "    <p>如果您没有访问过安全鱼开放平台，或没有进行上述操作，请忽略这封邮件。您不需要退订或进行其他进一步的操作。</p>\n" +
                "    <p>这是一封注册认证邮件，请点击以下链接确认：</p>\n" +
                "<a href=" + url + to + "&code=" + code + ">" + url + to + "&code=" + code + "</a>" +
                "    <p>如果链接不能点击，请复制地址到浏览器，然后直接打开。</p>\n" +
                "    <p>上述链接48小时有效。如果激活链接失效，请登录网站 <a href='http://app.forkeji.com'>http://app.forkeji.com </a>重新申请认证。</p>\n" +
                "    <p>感谢您注册安全鱼开放平台！</p>\n" +
                "    <div style=\"text-align: right;\">\n" +
                "        <p>安全鱼开放平台项目组</p>\n" +
                "        <p>" + dateString + "</p>\n" +
                "    </div>\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>";


        boolean bool = sendMails(subject, to, contents);
        return bool;

    }

    /**
     * 发送验证码
     *
     * @param to
     * @param code
     * @return
     */
    public static boolean sendEmailCode(String to, String code) {
        String subject = "安全鱼注册验证码";
        String dateString = getNowDateUtils();
        String contents = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>邮箱激活样式</title>\n" +
                "    <style>\n" +
                "        .bg{\n" +
                "            padding: 20px 30px;\n" +
                "            width: 1000px;\n" +
                "            background: -webkit-repeating-linear-gradient(#d6e4ed,white); /* Safari 5.1 - 6.0 */\n" +
                "            background: -o-repeating-linear-gradient(#d6e4ed , white); /* Opera 11.1 - 12.0 */\n" +
                "            background: -moz-repeating-linear-gradient(#d6e4ed , white); /* Firefox 3.6 - 15 */\n" +
                "            background: repeating-linear-gradient(#d6e4ed,  white); /* 标准的语法（必须放在最后） */\n" +
                "            overflow: hidden;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<div class=\"bg\">\n" +
                "    <p>尊敬的用户:</p>\n" +
                "    <p>您好！恭喜你注册成为安全鱼用户。</p>\n" +
                "    <p>如果您没有下载过安全鱼软件，或没有进行上述操作，请忽略这封邮件。您不需要退订或进行其他进一步的操作。</p>\n" +
                "    <p>这是一封注册认证邮件，您的验证码为：<span style=\"font-size: 24px;color: blue;\">" + code + "</span></p>\n" +
                "\n" +
                "    <p>上述验证码15分钟有效。如果验证码失效。请重新获取。</p>\n" +
                "    <p>感谢您注册安全鱼软件用户！</p>\n" +
                "    <div style=\"text-align: right;\">\n" +
                "        <p>安全鱼开发组</p>\n" +
                "        <p>" + dateString + "</p>\n" +
                "    </div>\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>";
        boolean bool = sendMails(subject, to, contents);
        return bool;

    }

    /**
     * 发送通知消息
     *
     * @param to
     * @param contents
     * @return
     */
    public static boolean sendEmailMassage(String to, String contents) {
        String subject = "通知消息";
        boolean bool = sendMails(subject, to, contents);
        return bool;

    }

    private static String getNowDateUtils() {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年 MM月 dd日");
        return formatter.format(new Date());
    }

    public static void main(String[] args) {
        String email = "1258722776@qq.com";
        boolean code = SendMailUtils.sendEmailCode(email, "36589");
        System.out.println(code);
    }


}
